package com.ruoyi;

import com.ruoyi.stock2.domain.*;
import com.ruoyi.stock2.mapper.STOCKMapper;
import com.ruoyi.stock2.service.*;
import com.ruoyi.stock2.utils.DateUtils2;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.*;
import java.math.BigDecimal;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.util.*;

@RunWith(SpringRunner.class)
@SpringBootTest
public class Type7toseq2seqTrain {
	private static final Logger log = LoggerFactory.getLogger(Type7toseq2seqTrain.class);
	@Autowired(required = false)
	STOCKMapper stockMapper;
	@Autowired(required = false)
	IFasttextTrainService iFasttextTrainService;
	@Autowired(required = false)
	ITRADEDATAService itradedataService;
	@Autowired(required = false)
	ISelectModelFromPcaService iSelectModelFromPcaService;
	@Autowired
	private ISelectModelFromPcaService selectModelFromPcaService;




	//@Test
	public void buildseq2seqTrainToTxt() {
		SelectModelFromPca selectModelFromPca = new SelectModelFromPca();
		selectModelFromPca.setType("type7");
		List<SelectModelFromPca> list = selectModelFromPcaService.selectSelectModelFromPcaList(selectModelFromPca);
		System.out.println(list.size() );
		File file = new File("/opt/seq2seq_type7_train.txt");
		BufferedWriter writer = null;
		try {
			if(!file.exists()){
				file.createNewFile();
			}else{
				file.delete();
				file.createNewFile();
			}
			writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, false), "utf-8"));

			for(int i = 0 ; i < list.size() ; i++){
				StringBuilder stringBuilderIt = new StringBuilder();
				TRADEDATA tradedata = new TRADEDATA();
				tradedata.setSymbol(list.get(i).getSymbol());
				tradedata.setDatetime(list.get(i).getDatetime());
				List<TRADEDATA> listinput = itradedataService.selectTradedataInput40Days(tradedata);
				List<TRADEDATA> listtarget = itradedataService.selectTradedataTarget40Days(tradedata);

				stringBuilderIt.append(listinput.get(0).getSymbol()).append(",");
				stringBuilderIt.append(DateUtils2.formatDateToString(listinput.get(0).getDatetime(),"yyyyMMdd")).append(",");
				System.out.println(stringBuilderIt);
				List<BigDecimal> lista = new ArrayList<BigDecimal>();
				for(TRADEDATA tradedata1 : listinput){
					lista.add(tradedata1.getCloseprice());
				}
				for(TRADEDATA tradedata1 : listtarget){
					lista.add(tradedata1.getCloseprice());
				}
				BigDecimal min = Collections.min(lista);

				for(int j = listinput.size()-1; j>0; j--){
					stringBuilderIt.append(listinput.get(j).getCloseprice().divide(min, 3, BigDecimal.ROUND_HALF_UP)).append(" ");
				}
				stringBuilderIt.append(listinput.get(0).getCloseprice().divide(min, 3, BigDecimal.ROUND_HALF_UP));
				stringBuilderIt.append(",");
				for(int k = 0; k<listtarget.size(); k++){
					stringBuilderIt.append(listtarget.get(k).getCloseprice().divide(min, 3, BigDecimal.ROUND_HALF_UP)).append(" ");
				}
				writer.write(stringBuilderIt + "\r\n");
				writer.flush();

			}

			writer.flush();
		} catch (IOException e1) {
			e1.printStackTrace();
		} finally {
			try {
				if (writer != null) {
					writer.close();
				}
			} catch (IOException  e) {
				e.printStackTrace();
			}
		}
	}

	//第三步：读取训练集文件，把每个数只保留一个
	//@Test
	public void read2oneword() {
		Path path = Paths.get("/opt/seq2seq_type7_train.txt");
		TreeSet<Double> set = new TreeSet();
		Charset charset = Charset.forName("utf-8");
		try (BufferedReader reader = Files.newBufferedReader(path, charset)) {
			String line = null;

			while ((line = reader.readLine()) != null) {
				String[] spline = line.split(",");
				if (spline.length == 4) {
					for (String a : spline[2].split(" ")) {
						set.add(Double.parseDouble(a));
					}
				}
			}
		} catch (IOException x) {
			System.err.format("IOException: %s%n", x);
		}
		StringBuffer buffer = new StringBuffer(1000000);
		// 增强for循环
		DecimalFormat df = new DecimalFormat("#.000");
		for (Double d : set) {
			buffer.append(df.format(d)).append(" ");
		}
		System.out.println(set.size());
		writeTxtFile(buffer.toString(), "/opt/seq2seq_type7_train_Set.txt");
	}


	public void writeTxtFile(String newStr, String fileName) {
		byte[] sourceByte = new byte[0];
		try {
			sourceByte = newStr.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		if (null != sourceByte) {
			try {
				File file = new File(fileName); // 文件路径（路径+文件名）
				if (!file.exists()) { // 文件不存在则创建文件，先创建目录
					File dir = new File(file.getParent());
					dir.mkdirs();
					file.createNewFile();
				}
				FileOutputStream outStream = new FileOutputStream(file); // 文件输出流用于将数据写入文件
				outStream.write(sourceByte);
				outStream.close(); // 关闭文件输出流
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
